package io.github.wslxm.springbootplus2.utils;

import io.github.wslxm.springbootplus2.core.config.error.ErrorException;
import io.github.wslxm.springbootplus2.starter.redis.config.error.RedisErrorException;
import io.github.wslxm.springbootplus2.starter.websocket.config.error.WebSocketErrorException;

import java.util.Arrays;

/**
 * 获取错误信息工具
 *
 * @author wangsong
 * @date 2023/05/30
 */
public class XjErrorMsgUtil {

    /**
     * 得到错误str
     *
     * @param e e
     * @return {@link String}
     */
    public static String getErrorStr(Exception e) {
        // 自定义异常
        if (e instanceof ErrorException) {
            ErrorException errorException = (ErrorException) e;
            String msg = errorException.getMsg();
            Integer code = errorException.getCode();
            return "code: " + code + " error: " + msg;
        } else if (e instanceof RedisErrorException) {
            RedisErrorException errorException = (RedisErrorException) e;
            String msg = errorException.getMsg();
            Integer code = errorException.getCode();
            String errorMsg = errorException.getErrorMsg();
            return "code: " + code + " error: " + msg + " errorMsg: "+ errorMsg;
        } else if (e instanceof WebSocketErrorException) {
            WebSocketErrorException errorException = (WebSocketErrorException) e;
            String msg = errorException.getMsg();
            Integer code = errorException.getCode();
            return "code: " + code + " error: " + msg ;
        } else {
            // 其他异常
            String exceptionClass = e.getClass().getName();
            StringBuffer errorDesc = new StringBuffer();
            errorDesc.append("\r\nException class: ").append(exceptionClass);
            errorDesc.append("\r\nError Message: ").append(e.getMessage());
            errorDesc.append("\r\nError Stack:\r\n");
            if (e.getStackTrace() != null) {
                Arrays.stream(e.getStackTrace()).forEach((i) -> {
                    errorDesc.append(i.toString()).append("\r\n");
                });
            }
            return errorDesc.toString();
        }
    }
}
